#include "communication-device-fingerprint.h"

CommunicationDeviceFingerPrint::CommunicationDeviceFingerPrint(FingerPrintManager *fingerPrintManager)
    : fingerPrintManager(fingerPrintManager)
{
	handle["add"]    = &CommunicationDeviceFingerPrint::add;
	handle["remove"] = &CommunicationDeviceFingerPrint::remove;
	handle["clear"]  = &CommunicationDeviceFingerPrint::clear;
}

void CommunicationDeviceFingerPrint::communication(SmartDevicenetProtocol &netProtocol, NetCommunication *netObj)
{
	//1控制门锁
	string command = netProtocol.getCommand();
	auto   func    = handle[command];
	if(!func)
	{
		return;
	}
	(this->*func)(netProtocol, netObj);
}

void CommunicationDeviceFingerPrint::add(SmartDevicenetProtocol &netProtocol,
                                         NetCommunication *      netObj)
{
	string   command = netProtocol.getCommand();
	uint32_t userId  = netProtocol.getUserId();
	bool     ok      = fingerPrintManager->recordFingerprint(userId);
	string   errmsg  = ok ? "" : "error";
	replay(netObj, command, errmsg);
}

void CommunicationDeviceFingerPrint::remove(SmartDevicenetProtocol &netProtocol,
                                            NetCommunication *      netObj)
{
	string   command = netProtocol.getCommand();
	uint32_t userid  = netProtocol.getUserId();
	bool     ok      = fingerPrintManager->deleteFingerprint(userid);
	string   errmsg  = ok ? "" : "error";
	replay(netObj, command, errmsg);
}

void CommunicationDeviceFingerPrint::clear(SmartDevicenetProtocol &netProtocol, NetCommunication *netObj)
{
	string command = netProtocol.getCommand();
	bool   ok      = fingerPrintManager->clearFingerprintLib();
	string errmsg  = ok ? "" : "error";
	replay(netObj, command, errmsg);
}

void CommunicationDeviceFingerPrint::replay(NetCommunication *netObj,
                                            const string &    command,
                                            const string &    errmsg,
                                            const string &    data)
{
	SmartDevicenetProtocol netProtocol;
	netProtocol.addOperation("fingerprint");
	netProtocol.addCommand(command);
	netProtocol.addResult(errmsg, data);
	string repalyJsonData = netProtocol.toString();

	vector<uint8_t> packet;
	packet.assign(repalyJsonData.begin(), repalyJsonData.end());
	cout << "------------udp发送----------------" << endl;
	bool ret = netObj->sendPacket(packet);
	if(ret != true)
	{
		fprintf(stderr, "Fail to sendPacket\n");
		return;
	}

	return;
}
